/******************************************************************************

    Copyright (C) 2010 Alessio Stalla (alessiostalla@gmail.com)

    This file is part of PrettyProlog.

    PrettyProlog is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    PrettyProlog is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with PrettyProlog; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

    See the file COPYING for further details.

 *****************************************************************************/

package prettyprolog.engine.syspreds;

import java.lang.reflect.Method;
import java.util.List;

import prettyprolog.datatypes.CharString;
import prettyprolog.datatypes.Constant;
import prettyprolog.datatypes.JavaObject;
import prettyprolog.datatypes.Real;
import prettyprolog.datatypes.Substitution;
import prettyprolog.datatypes.Symbol;
import prettyprolog.datatypes.Term;
import prettyprolog.datatypes.Variable;
import prettyprolog.engine.Engine;
import prettyprolog.engine.Theory;

/**
 * Implements the syspred/3 system predicate, used to register a system predicate or to check whether
 * a given symbol names a system predicate. The possible usage patterns are:
 * <ul>
 *   <li><code>syspred(name, nargs, Variable)</code> - binds Variable to the system predicate called name taking nargs
 *   arguments, if it exists; else fails.</li>
 *   <li><code>syspred(name, nargs, class_name)</code> - registers an instance of class_name as a system predicate called name taking nargs
 *   arguments. nargs can be a variable: in that case the number of arguments will be extracted from the system predicate
 *   and the variable will be bound to it. class_name must be a string naming a Java class that extends SystemPredicate and that has a public static getInstance() method
 *   returning the singleton instance of the system predicate. An error is signalled if class_name does not fulfill these requirements
 *   or if the system predicate does not take the required number of arguments.</li>
 * </ul>
 * @author Alessio Stalla
 *
 */
public class Syspred extends SystemPredicate {

	private static final Syspred inst = new Syspred();

	private Syspred() {
		super(3);
	}

	/** Returns the only instance of this system predicate. */
	public static Syspred getInstance() {
		return inst;
	}

	protected SyspredEffect doCall(Engine en, Substitution subst, List<Term> args) throws SyspredException {
		Term syspred = args.get(2);
		Symbol name;
		if(args.get(0) instanceof CharString) {
			name = prettyprolog.datatypes.Namespace.current().intern(((CharString) args.get(0)).getString());
		} else if(args.get(0) instanceof Constant) {
			name = ((Constant) args.get(0)).getSymbol();
		} else {
			throw new SyspredException("Syspred name must be a constant or a string: " + args.get(0));
		}
		if(syspred instanceof CharString) {
			Theory th = en.getTheory(); 
			Term nargs = registerSyspred(syspred, name, args.get(1), th);
			Substitution s2 = en.getUnificationAlgorithm().unify(args.get(1), nargs);
			return new SyspredEffect(false, subst.compose(s2));
		} else if(syspred instanceof Variable) {
			if(args.get(1) instanceof Real) {
				int nargs = (int) ((Real) args.get(1)).getValue();
				SystemPredicate sp = en.getTheory().systemPredicate(name, nargs);
				if(sp != null) {
					Substitution s2 = en.getUnificationAlgorithm().unify(syspred, new JavaObject(sp));
					return new SyspredEffect(false, subst.compose(s2));
				} else {
					return new SyspredEffect(true, subst);	
				}
			} else {
				throw new SyspredException("Not a number: " + args.get(1));
			}
		} else {
			throw new SyspredException(syspred + " must be a string or a variable");
		}
	}

	protected Term registerSyspred(Term syspred, Symbol name, Term nargs, Theory th) throws SyspredException {
		try {
			Class<?> c = Class.forName(((CharString) syspred).getString());
			if(SystemPredicate.class.isAssignableFrom(c)) {
				Method getInstance = c.getMethod("getInstance");
				SystemPredicate sp = (SystemPredicate) getInstance.invoke(null);
				if(nargs instanceof Real) {
					if(!(sp.getRequiredArgumentsCount() == ((Real) nargs).getValue())) {
						throw new SyspredException("Wrong number of arguments: " + nargs + " declared but " + sp + " takes " + sp.getRequiredArgumentsCount());
					}
				} else if(!(nargs instanceof Variable)) {
					throw new SyspredException(nargs + " should be a number or a variable");
				}
				th.registerSystemPredicate(name, sp);
				return new Real(sp.getRequiredArgumentsCount());
			} else {
				throw new SyspredException(syspred + " does not name a class extending SystemPredicate: " + c);
			}
		} catch(Exception e) {
			throw new SyspredException("Error registering syspred " + syspred, e);
		}
	}
	
	public boolean isBacktrackable() {
		return false;
	}

	public String toString() {
		return super.toString() + " (syspred/3)";
	}
}